package com.xxg.renrenorder.service;

import com.xxg.renrencommon.domain.filedenum.RedisKeyEnum;
import com.xxg.renrencommon.domain.result.BaseResult;
import com.xxg.renrencommon.exception.exceptionenum.OrderExceptionCodeCodeEnum;
import com.xxg.renrenorder.dao.CommissionSettingInfoDao;
import com.xxg.renrenorder.dao.bean.CommissionSettingInfo;
import com.xxg.renrenorder.domain.query.SaveCommissionQuery;
import com.xxg.renrenorder.util.RedisUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 类说明
 *
 * @author szj
 * @date 2022/1/4
 */
@Service
@Slf4j
@AllArgsConstructor
public class CommissionSettingServiceImpl implements CommissionSettingService{
    private final CommissionSettingInfoDao commissionSettingInfoDao;
    private final RedisUtil redisUtil;

    @Override
    public BaseResult<List<CommissionSettingInfo>> list() {
        return new BaseResult<>(commissionSettingInfoDao.findAll());
    }

    @Override
    public BaseResult<Void> save(SaveCommissionQuery query) {
        CommissionSettingInfo commissionSettingInfo = commissionSettingInfoDao.findByGroupId(query.getGroupId());
        Boolean absent = redisUtil.setIfAbsent(String.format(RedisKeyEnum.SET_COMMISSION_KEY.key(), query.getGroupId()), query.getGroupId(), RedisKeyEnum.SET_COMMISSION_KEY.time());
        if (!absent) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.SET_COMMISSION_KEY_DUP);
        }
        if (commissionSettingInfo == null) {
            commissionSettingInfo = new CommissionSettingInfo();
            commissionSettingInfo.setCreateTime(new Date());
            commissionSettingInfo.setGroupId(query.getGroupId());
        }else {
            commissionSettingInfo.setUpdateTime(new Date());
        }
        commissionSettingInfo.setRatio(query.getRatio());
        commissionSettingInfoDao.save(commissionSettingInfo);
        redisUtil.del(String.format(RedisKeyEnum.SET_COMMISSION_KEY.key(), query.getGroupId()));
        return new BaseResult<>();
    }
}
